<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Config;
use think\Db;
use app\admin\model\Cource;
use app\admin\model\My_vegetables; 
use app\admin\model\My_Index; 
use app\admin\model\My_props;
use app\admin\model\My_plant;
use app\admin\model\Granary;
/**
 * 首页接口
 */
class Index extends Api
{
    // protected $noNeedLogin = ['mp3_detail','index','mp3_list'];
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new \app\common\model\Order;
        // $this->user_id = 2;
    }  

     /**
     * 首页获取数据
     * @ApiSummary  (my_data是个人信息，my_feiliao是肥料列表,my_quchongji是驱虫剂列表,index是九块地的种子列表，健名是location)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/index)
     * @ApiReturn({
        {
      "code": 1,
      "msg": "请求成功",
      "time": "1594518330",
      "data": {
        "my_data": {
          "avatar": "https://wx.qlogo.cn/mmopen/vi_32/Ee3rJFn8tPxyXnbLgdCcJlYND6f28b38JAs8h23vyP7dribYsibWlptFmp1sBibd6MgE9wslOOKGkB05Ht2Fe2BSg/132",
          "gold": "560.00",//金币余额
          "nickname": "Vicky",
          "land_num": 1//土地数量
        },
        // 我的肥料
        "my_feiliao": [
          {
            "id": 8,
            "user_id": 2,
            "updatetime": 1594457748,
            "image": "http://nongchang.com/uploads/20200709/3518f66009ba748df0c0c7f54a45dc9f.png",
            "num": 1,
            "props_id": 3,
            "name": "普通肥料",
            "text": "普通肥料一次可以加20经验值",
            "add_gold": "20.00",
            "add_experience": "20.00",
            "status": "advanced"
          }
        ],
        // 我的驱虫剂
        "my_quchongji": [
          {
            "id": 9,
            "user_id": 2,
            "updatetime": 1594457752,
            "image": "http://nongchang.com/uploads/20200711/56b2883229fe2d75293e112db97b4a18.png",
            "num": 2,
            "props_id": 8,
            "name": "驱虫剂",
            "text": "驱虫剂一次可以加20经验值",
            "add_gold": "20.00",
            "add_experience": "20.00",
            "status": "deworming"
          }
        ],
        "index": {
            //键名是location的位置                   
          "1": {
            "id": 1,
            "user_id": 2,
            "vegetables_id": 1,
            "location": 1,
            "image": "http://nongchang.com/uploads/20200709/fe6f45e7df5f4e9a84e6c4eb44acc267.png",
            "name": "新鲜蔬菜",
            "water_gold": "10.00",
          },
          "2": {
            "id": 5,
            "user_id": 2,
            "vegetables_id": 1,
            "location": 2,
            "image": "http://nongchang.com/uploads/20200709/fe6f45e7df5f4e9a84e6c4eb44acc267.png",
            "name": "苹果树苗",
            "water_gold": "10.00",
          }
        }
      }
    }
     })
     */
    public function index(){
        $return['my_data'] = Db::name('user')->where('id',$this->user_id)->field('avatar,gold,nickname,land_num')->find();

        $return['my_feiliao'] = Db::name('my_props')->where('user_id',$this->user_id)->where('status','advanced')->select();
        $return['my_quchongji'] = Db::name('my_props')->where('user_id',$this->user_id)->where('status','deworming')->select();

        $return['index'] = Db::name('index')->where(['user_id'=>$this->user_id])->select();
        $return['index'] = array_column($return['index'], null,'location');        
        $this->success('请求成功',$return);
    }

    /**
     * 我的仓库、粮仓
     * @ApiSummary  (vegetables是我的种子列表，my_feiliao是肥料列表,my_quchongji是驱虫剂列表)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/my_warehouse)
     * @ApiReturn({
      {
  "code": 1,
  "msg": "我的仓库、粮仓",
  "time": "1594609825",
  "data": {
    // 仓库列表
    "cangku": {
      // 肥料列表
      "my_feiliao": [
        {
          "id": 8,
          "user_id": 2,
          "updatetime": 1594457748,
          "image": "http://nongchang.com/uploads/20200709/3518f66009ba748df0c0c7f54a45dc9f.png",
          "num": 2,
          "props_id": 3,//道具id（该值是唯一的）
          "name": "普通肥料",
          "text": "普通肥料一次可以加20经验值",
          "add_gold": "20.00",
          "add_experience": "20.00",
          "status": "advanced"
        }
      ],
      // 驱虫剂列表
      "my_quchongji": [
        {
          "id": 9,
          "user_id": 2,
          "updatetime": 1594457752,
          "image": "http://nongchang.com/uploads/20200711/56b2883229fe2d75293e112db97b4a18.png",
          "num": 2,
          "props_id": 8,//道具id（该值是唯一的）
          "name": "驱虫剂",
          "text": "驱虫剂一次可以加20经验值",
          "add_gold": "20.00",
          "add_experience": "20.00",
          "status": "deworming"
        }
      ],
      //我的种子
      "vegetables": [
        {
          "id": 6,
          "vegetables_id": 1,//种子id
          "name": "苹果树苗",
          "image": "http://nongchang.com/uploads/20200709/fe6f45e7df5f4e9a84e6c4eb44acc267.png",
          "num": 0,
          "user_id": 2,
          "updatetime": 1594447629,
          "water_gold": "10.00",
          "text": "浇水一次可以加10金币"
        }
      ]
    },
    //我的粮仓
    "liangcang": [
      {
        "id": 2,
        "user_id": 2,
        "plant_id": 1,//果实id
        "num": 10,
        "image": "http://nongchang.com/uploads/20200709/c66b6d5156ba03e82a447f4cb2e921b4.png",
        "updatetime": 1594538634,
        "fruit_text": "苹果至少10个才能配送"
      }
    ]
  }
}
      })
     */
    public function my_warehouse(){
        $return['cangku']['my_feiliao'] = Db::name('my_props')->where('user_id',$this->user_id)->where('status','advanced')->select();
        $return['cangku']['my_quchongji'] = Db::name('my_props')->where('user_id',$this->user_id)->where('status','deworming')->select();
        $return['cangku']['vegetables'] = Db::name('my_vegetables')->where('user_id',$this->user_id)->select();

        $return['liangcang'] = Db::name('granary')->where('user_id',$this->user_id)->select();
        $this->success('我的仓库、粮仓',$return);
    }

     /**
     * 使用道具
     * @ApiSummary  (如果不传道具id过来就是浇水，但是要传蔬菜id过来，后台我设置了不同的蔬菜浇水产生的金币是不一样的。   使用道具可以不传蔬菜id和位置过来，因为道具是独立加金币的。   小树苗id和首页蔬菜种子id传其中一个过来)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/use_props)
     * @ApiParams   (name="props_id",type=int,required=false,description="道具id")
     * @ApiParams   (name="vegetables_id",type=int,required=true,description="首页蔬菜种子id")
     * @ApiParams   (name="location",type=int,required=true,description="位置id")
     * @ApiParams   (name="plant_id",type=int,required=true,description="小树苗id")
     * @ApiReturn({
        //第一种情况
        {
          "code": 0,
          "msg": "该蔬菜今天已经浇过水了",
          "time": "1594520913",
          "data": null
        }
        //给首页蔬菜使用道具
        {
          "code": 1,
          "msg": "道具使用成功,金币增加20.00",//或者是小树苗经验值增加多20.00
          "time": "1594522376",
          "data": null
        }
        //给小树苗使用道具
        {
          "code": 1,
          "msg": "道具使用成功,经验值已满,收成了苹果5个",
          "time": "1594532543",
          "data": null
        }
        
     })
     */
    public function use_props(){
        $vegetables_id = input('vegetables_id');
        $location = input('location');
        $props_id = input('props_id');
        $plant_id = input('plant_id'); 
        // water
        if(empty($props_id)){
            if(!empty($vegetables_id)){
                $My_Index = new My_Index();
                if(empty($location))$this->error('位置参数必填');
                $My_index_data = $My_Index->where(['location'=>$location,'user_id'=>$this->user_id,'vegetables_id'=>(int)$vegetables_id])->find();
                if(empty($My_index_data))$this->error('数据找不到');


                if(date('Y-m-d') == date('Y-m-d',$My_index_data['water_day']))$this->error('该蔬菜今天已经浇过水了');

                $water_day = time();

                Db::name('user')->where('id',$this->user_id)->setInc('gold',$My_index_data['water_gold']);

                $res = $My_index_data->save(['water_day'=>$water_day]);
                if($res)$this->success('浇水成功,金币增加'.$My_index_data['water_gold']);
            
            // 给小树苗浇水
            }else{
                $status = 0;

                $My_plant = new My_plant();
                $My_plant_data = $My_plant->where(['user_id'=>$this->user_id,'plant_id'=>(int)$plant_id])->find();
                if(empty($My_plant_data))$this->error('数据找不到');

                if(date('Y-m-d') == date('Y-m-d',$My_plant_data['water_day']))$this->error('该小树苗今天已经浇过水了');

                $water_day = time();
                
                $remaining_experience = (int)$My_plant_data['remaining_experience'] - (int)$My_plant_data['water_experience'];
                // 结果实

                if($remaining_experience<=0){
                    $status = 1;
                    $remaining_experience = $My_plant_data['experience'];
                    $now_experience = 0;
                    $percentage = 0;

                    // 先查找是否存在
                    $Granary = new Granary();
                    $my_granary = $Granary->where(['user_id'=>$this->user_id,'plant_id'=>$plant_id])->find();

                    $plant_data = Db::name('plant')->where('id',$plant_id)->find();
                    $fruit_num = $plant_data['fruit_num'];

                    if($my_granary){
                        $my_granary->setInc('num',(int)$fruit_num);
                    }else{
                        $insert['num'] = $fruit_num;
                        $insert['user_id'] = $this->user_id;
                        $insert['plant_id'] = $plant_id;
                        $insert['updatetime'] = time();
                        $insert['image'] = $plant_data['image'];
                        $insert['fruit_text'] = $plant_data['fruit_text'];

                        $res2 = $Granary->save($insert);
                    }

                }else{
                    $now_experience = (int)$My_plant_data['now_experience'] + (int)$My_plant_data['water_experience'];
                    $percentage = $now_experience/$My_plant_data['experience']*100;
                }
                $res = $My_plant_data->save(['water_day'=>$water_day,'percentage'=>$percentage,'now_experience'=>$now_experience,'remaining_experience'=>$remaining_experience]);
                    
                if($res){
                    if($status){
                        $this->success('道具使用成功,经验值已满,收成了'.$plant_data['fruit_name'].$plant_data['fruit_num'].'个');
                    }else{
                        $this->success('浇水成功,经验值增加'.$My_plant_data['water_experience']);
                    }
                }
                
            }
            
            
        }else{
            $My_props = new My_props();
            $my_props_data = $My_props->where(['user_id'=>$this->user_id,'props_id'=>$props_id])->find();

            if($my_props_data['num']<=0)$this->error('道具用完了，请到商场购买');
            
            $my_props_data->setDec('num');

            if(!empty($vegetables_id)){

                Db::name('user')->where('id',$this->user_id)->setInc('gold',$my_props_data['add_gold']);

                $this->success('道具使用成功,金币增加'.$my_props_data['add_gold']);
            // 给小树苗使用道具
            }else{
                $status = 0;

                $My_plant = new My_plant();
                $My_plant_data = $My_plant->where(['user_id'=>$this->user_id,'plant_id'=>(int)$plant_id])->find();
                if(empty($My_plant_data))$this->error('数据找不到');

                $remaining_experience = (int)$My_plant_data['remaining_experience'] - (int)$my_props_data['add_experience'];
                // 结果实
                if($remaining_experience<=0){
                    $status = 1;
                    
                    $remaining_experience = $My_plant_data['experience'];
                    $now_experience = 0;
                    $percentage = 0;

                    // 先查找是否存在
                    $Granary = new Granary();
                    $my_granary = $Granary->where(['user_id'=>$this->user_id,'plant_id'=>$plant_id])->find();

                    $plant_data = Db::name('plant')->where('id',$plant_id)->find();
                    $fruit_num = $plant_data['fruit_num'];

                    if($my_granary){
                        $my_granary->setInc('num',(int)$fruit_num);
                    }else{
                        $insert['num'] = $fruit_num;
                        $insert['user_id'] = $this->user_id;
                        $insert['plant_id'] = $plant_id;
                        $insert['updatetime'] = time();
                        $insert['image'] = $plant_data['image'];
                        $insert['fruit_text'] = $plant_data['fruit_text'];

                        $res2 = $Granary->save($insert);
                    }

                }else{
                    $now_experience = (int)$My_plant_data['now_experience'] + (int)$my_props_data['add_experience'];
                    $percentage = $now_experience/$My_plant_data['experience']*100;
                }

                $res = $My_plant_data->save(['percentage'=>$percentage,'now_experience'=>$now_experience,'remaining_experience'=>$remaining_experience]);

                if($res){
                    if($status){
                        $this->success('道具使用成功,经验值已满,收成了'.$plant_data['fruit_name'].$plant_data['fruit_num'].'个');
                    }else{
                        $this->success('道具使用成功,经验值增加'.$my_props_data['add_experience']);
                    }
                }
            }
            
        }
    }

     /**
     * 首页种植
     * @ApiSummary  ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/planting)
     * @ApiParams   (name="location",type=int,required=true,description="位置")
     * @ApiParams   (name="vegetables_id",type=int,required=true,description="首页蔬菜种子id")
     
     */
    public function planting(){
        
        $param = input();
        $param['user_id'] = $this->user_id;
        $location = $param['location'];

        $now_location_data = Db::name('index')->where(['user_id'=>$this->user_id,'location'=>$location])->find();
        if($now_location_data)$this->error('该地已种植种子了');

        $My_vegetables = new My_vegetables();

        $vegetables_id = input('vegetables_id');
        $vegetables_data = $My_vegetables->field('num,image,name,water_gold')->where(['vegetables_id'=>$vegetables_id,'user_id'=>$this->user_id])->find();
        if($vegetables_data['num']<=0)$this->error('种子数不够了');
        $param = array_merge($param,$vegetables_data->toArray());
        unset($param['num']);
        $res = Db::name('index')->insert($param);

        if($res){
            // 种子数量减少
            $vegetables_data->setDec('num',1);
            $this->success('种植成功');
        }
    }

    /**
     * 我的农作物页面
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/my_adopt)
     * @ApiReturn({
        {
          "code": 1,
          "msg": "我的农作物",
          "time": "1594524264",
          "data": [
            {
              "id": 4,
              "name": "苹果树",//小树苗名称
              "user_id": 2,
              "plant_id": 2,
              "now_experience": "0.00",//当前经验值
              "remaining_experience": "10.00",//剩余经验值
              "image": "http://nongchang.com/uploads/20200712/e012bdeca40527538eae90690b6cffb4.jpg",
              "percentage": "0.00",//百分比
              "updatetime": 1594523751,
              "fruit_name": "苹果",//小树苗果实的名称
              "water_experience": "10.00"
            }
          ]
        }
     })
     */
    
    public function my_adopt(){
        $my_adopt = Db::name('my_plant')->order('updatetime desc')->select();
        $this->success('我的领养',$my_adopt);
    }
    /**
     * 果实兑换成金币,或者是邮寄到家(传了手机号码就代表邮寄)
     * @param int $plant_id
     * @param int $num     
     * @param int $phone     
     * @param int $contact_name     
     * @param int $detail     
     */
    public function change(){
        $plant_id = input('plant_id');
        $num = input('num');
        $phone = input('phone');
        $contact_name = input('contact_name');
        $detail = input('detail');

        $Granary = new Granary();
        $my_granary = $Granary->where(['user_id'=>$this->user_id,'plant_id'=>$plant_id])->find();
        if($my_granary['num']<$num)$this->error('粮仓的果实数量不足');

        if(empty($phone)){
            $plant_data = Db::name('plant')->where('id',$plant_id)->find();
            $change_gold = (int)$plant_data['fruit_gold']*(int)$num;

            Db::name('user')->where('id',$this->user_id)->setInc('gold',$change_gold);
            $my_granary->setDec('num',(int)$num);

            $this->success('成功兑换了'.$change_gold.'金币');
        }else{

            //fruit_limit first_num first_fee renewal renewal_fee
            $plant_data = Db::name('plant')->where('id',$plant_id)->find();

            if($plant_data['fruit_limit']>$num)$this->error($plant_data['fruit_name'].'至少'.$plant_data['fruit_limit'].'个起才能邮寄');
            
            // 果实首件（个）
            if($plant_data['first_num']>=$num){
                $params['total_price'] = $plant_data['first_fee'];
            // 续费
            }else{
                //续费个数
                $renewal_num = (int)$num-(int)$plant_data['first_num'];
                $params['total_price'] = ceil((int)$renewal_num/(int)$plant_data['renewal'])*$plant_data['renewal_fee']+$plant_data['first_fee'];
            }
            $params['num'] = $num;
            $params['detail'] = $detail;
            $params['good_id'] = $plant_id;
            $params['spec_type'] = '50';
            $params['user_id'] = $this->user_id;
            $params['pay_type'] = '20';
            $params['image'] = $plant_data['fruit_image'];
            $params['name'] = $plant_data['fruit_name'];
            $params['contact_name'] = $contact_name;
            $order_no = $this->model->order_add($params);

            // 发起微信支付
            $this->init_wx_pay_for_wxapp();

            $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();

            $payment = $this->wxapp->payment;
            // halt($payment);
            $attributes = [
              'trade_type'       => 'JSAPI',
              'body'             => '农场',
              'detail'           => '农场',
              'out_trade_no'     => $order_no,
              'openid'           => $third['openid'],
              'total_fee'        => $params['total_price']*100,
              'notify_url'       => Config::get('site.cdnurl').'/api/order/callback_for_wxapp',
            ];

            $order_detail = new WXPAY_ORDER($attributes);
            $result = $payment->prepare($order_detail);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
              $prepayId = $result->prepay_id;
              $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
              return $this->success('订单创建成功,预支付成功',$config);
            }
            return $this->error('微信支付调用失败',$result);
        }
        
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => true,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }


  

    

  

}
